<template>
  <m-modal
    v-model="visible"
    :title="$t('c_path')"
    class="v-time-series-chart"
    :width="width"
    :mask="mask"
    :okLoading="okLoading"
    :visible="visible"
    resizable
    :okText="$t('confirm')"
    :cancelText="$t('cancel')"
    @cancel="handleCancel"
    @ok="handleOK"
  >
    <div class="sim_selector_content">
      <sim-select-tree
        :treeData="treeData"
        :selectedId="selectedId"
      />
    </div>
  </m-modal>
</template>

<script lang="ts">
import SelectTree from "./SelectTree.vue";
import { defineComponent, reactive, ref } from "vue";

export default defineComponent({
  name: "sim-tree-selector",
  components: {
    "sim-select-tree": SelectTree
  },
  props: {
    treeData: Object
  },
  setup() {

    let events = reactive({}) as any;
    let width = ref(400);
    let visible = ref(true);
    let mask = ref(true);
    let okLoading = ref(false);

    let selectedId = ref("");
    let parentId = ref("");
    return {
      events, width, visible, okLoading, selectedId, mask, parentId
    };
  },
  mounted() {
    this.events["sim-cancel-tree-select"] = this.handleCancelSelect;
    this.events["sim-tree-select"] = this.handleSelect;

    app.$bus.onBatch(this.events);
  },
  methods: {

    handleSelect(selectedInfo: { selectedId?: string, parentId?: string}) {
      this.selectedId = selectedInfo.selectedId ? selectedInfo.selectedId : "";
      this.parentId = selectedInfo.parentId ? selectedInfo.parentId : "";
    },

    handleCancelSelect() {
      this.selectedId = "";
    },

    handleCancel() {
      this.visible = false;
      app.$bus.offBatch(this.events);
      this.$emit('close');
    },

    handleOK() {
      this.visible = false;
      app.$bus.offBatch(this.events);
      if (this.selectedId === "") {
        this.$emit('close');
      } else {
        this.$emit('sure', {
          selectedId: this.selectedId,
          parentId: this.parentId
        });
      }
    },
  }
});
</script>

<style lang="scss" scoped>
.v-time-series-chart {
  .sim_selector_content {
    margin: 8px;
  }
}
</style>
